#include "auth_api_handler.h"
#include "auth_manager.h"
#include "base_log.h"
#include <nlohmann/json.hpp>
#include <string>
#include <unordered_map>

namespace El {
namespace Restful {

using json = nlohmann::json;

WebServer::HttpResponse HandleAuthLogin(const WebServer::HttpRequest &req)
{
    WebServer::HttpResponse response;
    response.content_type = "application/json";

    try {
        json request_data = json::parse(req.body);
        std::string username = request_data["username"].get<std::string>();
        std::string password = request_data["password"].get<std::string>();
        std::string device_id = request_data["device_id"].get<std::string>();
        bool remember_me = request_data.value("remember_me", false);

        json device_info = request_data.value("device_info", json::object());

        UserSession session;
        if (AuthManager::GetInstance().ValidateLogin(username, password, device_id, remember_me, session)) {
            // 登录成功，将token添加到web server的token列表中
            WebServer::IHttpServer::GetInstance().AddBearerToken(session.access_token);

            json data = {{"code", 200},
                         {"message", "Login successful"},
                         {"data",
                          {{"access_token", session.access_token},
                           {"refresh_token", session.refresh_token},
                           {"token_type", "Bearer"},
                           {"expires_in", 3600},
                           {"user",
                            {{"username", session.username},
                             {"role", session.role},
                             {"permissions", {"camera.view", "camera.control"}},
                             {"last_login", "2024-03-20T02:00:00Z"},
                             {"last_login_ip", "192.168.1.100"}}}}},
                         {"error", nullptr}};
            response.status_code = 200;
            response.body = data.dump();
        } else {
            response.status_code = 401;
            json error = {{"code", 401},
                          {"message", "Invalid credentials"},
                          {"data", nullptr},
                          {"error", "Invalid username or password"}};
            response.body = error.dump();
        }
    } catch (const std::exception &e) {
        LOG_ERROR("Failed to parse login request: {}", e.what());
        response.status_code = 400;
        json error = {{"code", 400}, {"message", "Invalid request format"}, {"data", nullptr}, {"error", e.what()}};
        response.body = error.dump();
    }

    return response;
}

WebServer::HttpResponse HandleAuthRefresh(const WebServer::HttpRequest &req)
{
    WebServer::HttpResponse response;
    response.content_type = "application/json";

    auto it = req.headers.find("Authorization");
    if (it == req.headers.end() || it->second.substr(0, 7) != "Bearer ") {
        response.status_code = 401;
        json error = {{"code", 401},
                      {"message", "Missing or invalid Authorization header"},
                      {"data", nullptr},
                      {"error", "Authorization header must start with Bearer"}};
        response.body = error.dump();
        return response;
    }

    std::string refresh_token = it->second.substr(7);
    UserSession session;
    if (AuthManager::GetInstance().RefreshToken(refresh_token, session)) {
        json data = {{"code", 200},
                     {"message", "Token refreshed successfully"},
                     {"data", {{"access_token", session.access_token}, {"token_type", "Bearer"}, {"expires_in", 3600}}},
                     {"error", nullptr}};
        response.status_code = 200;
        response.body = data.dump();
    } else {
        response.status_code = 401;
        json error = {{"code", 401},
                      {"message", "Invalid refresh token"},
                      {"data", nullptr},
                      {"error", "The refresh token is invalid or expired"}};
        response.body = error.dump();
    }

    return response;
}

WebServer::HttpResponse HandleAuthLogout(const WebServer::HttpRequest &req)
{
    WebServer::HttpResponse response;
    response.content_type = "application/json";

    auto it = req.headers.find("Authorization");
    if (it == req.headers.end() || it->second.substr(0, 7) != "Bearer ") {
        response.status_code = 401;
        json error = {{"code", 401},
                      {"message", "Missing or invalid Authorization header"},
                      {"data", nullptr},
                      {"error", "Authorization header must start with Bearer"}};
        response.body = error.dump();
        return response;
    }

    std::string access_token = it->second.substr(7);
    if (AuthManager::GetInstance().Logout(access_token)) {
        // 登出成功，从web server的token列表中移除token
        WebServer::IHttpServer::GetInstance().RemoveBearerToken(access_token);

        response.status_code = 200;
        json data = {{"code", 200}, {"message", "Logged out successfully"}, {"data", nullptr}, {"error", nullptr}};
        response.body = data.dump();
    } else {
        response.status_code = 401;
        json error = {{"code", 401},
                      {"message", "Invalid access token"},
                      {"data", nullptr},
                      {"error", "The access token is invalid or expired"}};
        response.body = error.dump();
    }

    return response;
}

void RegisterAuthApiHandlers()
{
    // 注册认证相关的API处理器
    WebServer::IHttpServer &server = WebServer::IHttpServer::GetInstance();

    // 将登录接口添加到免鉴权列表
    server.AddAuthExemptUrl("^/v1/auth/login$");

    server.RegisterHandler("POST", "^/v1/auth/login$", HandleAuthLogin);
    server.RegisterHandler("POST", "^/v1/auth/refresh$", HandleAuthRefresh);
    server.RegisterHandler("POST", "^/v1/auth/logout$", HandleAuthLogout);
}

} // namespace Restful
} // namespace El
